package com.sznaner.tool.util;

import android.content.Context;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;


import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MyPathUtil {


    public static String MyPhotos = "/MyPhotos";

    //获取外置SD卡路径
    public static String getSdcardPath( ){

        StorageManager mStorageManager = (StorageManager) NRTool.context().getSystemService(Context.STORAGE_SERVICE);
        String sdcard_path = null;
        try{
            Class<?> MyVolumeInfo = Class.forName("android.os.storage.VolumeInfo");
            Class<?> MyStorageManager = Class.forName("android.os.storage.StorageManager");
            Class<?> MyDiskInfo  = Class.forName("android.os.storage.DiskInfo");

            Method myGetVolumes = MyStorageManager.getMethod("getVolumes");
            Method myGetDescriptionComparator = MyVolumeInfo.getMethod("getDescriptionComparator");
            Method myGetType = MyVolumeInfo.getMethod("getType");
            Method myGetDisk = MyVolumeInfo.getMethod("getDisk");
            Method myIsSd = MyDiskInfo.getMethod("isSd");
            Method myGetState = MyVolumeInfo.getMethod("getState");
            Method myGetPath = MyVolumeInfo.getMethod("getPath");
            myGetPath.setAccessible(true);
            Field TYPE_PUBLIC = MyVolumeInfo.getField("TYPE_PUBLIC");
            TYPE_PUBLIC.setAccessible(true);
            Field STATE_MOUNTED = MyVolumeInfo.getField("STATE_MOUNTED");
            STATE_MOUNTED.setAccessible(true);

            myGetVolumes.setAccessible(true);
            myGetDescriptionComparator.setAccessible(true);
            myGetType.setAccessible(true);
            myGetDisk.setAccessible(true);
            myIsSd.setAccessible(true);
            myGetState.setAccessible(true);

            final List<Object> volumes = (List<Object>) myGetVolumes.invoke(mStorageManager);
            Collections.sort(volumes, (Comparator<Object>)myGetDescriptionComparator.invoke(null));

            for (Object vol : volumes) {
                if (myGetType.invoke(vol).equals(TYPE_PUBLIC.get(vol)) ) {
                    Object disk = myGetDisk.invoke(vol);
                    if (disk != null) {
                        if ((boolean) myIsSd.invoke(disk)) {
                            //sdcard dir
                            int status = (int)myGetState.invoke(vol);
                            if (status ==  (int)STATE_MOUNTED.get(vol)) {
                                File sdcardDir =(File) myGetPath.invoke(vol);
                                sdcard_path = sdcardDir.getAbsolutePath();
                            }
                        }
                    }
                }
            }} catch (Exception e) {
            //Log.d(TAG+"getExternalPath--", " e:" + e);
        }
        return sdcard_path;
    }
    //获取USB路径
    public static String getUsbPath(){
        StorageManager mStorageManager = (StorageManager) NRTool.context().getSystemService(Context.STORAGE_SERVICE);
        String usb_path = null;
        try {
            Class<?> MyVolumeInfo = Class.forName("android.os.storage.VolumeInfo");
            Class<?> MyStorageManager = Class.forName("android.os.storage.StorageManager");
            Class<?> MyDiskInfo  = Class.forName("android.os.storage.DiskInfo");

            Method myGetVolumes = MyStorageManager.getMethod("getVolumes");
            Method myGetDescriptionComparator = MyVolumeInfo.getMethod("getDescriptionComparator");
            Method myGetType = MyVolumeInfo.getMethod("getType");
            Method myGetDisk = MyVolumeInfo.getMethod("getDisk");
            Method myIsSd = MyDiskInfo.getMethod("isSd");
            Method myIsUsb = MyDiskInfo.getMethod("isUsb");
            Method myGetState = MyVolumeInfo.getMethod("getState");
            Method myGetPath = MyVolumeInfo.getMethod("getPath");
            myGetPath.setAccessible(true);
            Field TYPE_PUBLIC = MyVolumeInfo.getField("TYPE_PUBLIC");
            TYPE_PUBLIC.setAccessible(true);
            Field STATE_MOUNTED = MyVolumeInfo.getField("STATE_MOUNTED");
            STATE_MOUNTED.setAccessible(true);

            myGetVolumes.setAccessible(true);
            myGetDescriptionComparator.setAccessible(true);
            myGetType.setAccessible(true);
            myGetDisk.setAccessible(true);
            myIsSd.setAccessible(true);
            myIsUsb.setAccessible(true);
            myGetState.setAccessible(true);

            final List<Object> volumes = (List<Object>) myGetVolumes.invoke(mStorageManager);
            Collections.sort(volumes, (Comparator<Object>)myGetDescriptionComparator.invoke(null));

            for (Object vol : volumes) {
                if (myGetType.invoke(vol).equals(TYPE_PUBLIC.get(vol)) ) {
                    Object disk = myGetDisk.invoke(vol);
                    if (disk != null) {
                        if ((boolean) myIsUsb.invoke(disk)) {
                            //sdcard dir
                            int status = (int)myGetState.invoke(vol);
                            if (status ==  (int)STATE_MOUNTED.get(vol)) {
                                File sdcardDir =(File) myGetPath.invoke(vol);
                                usb_path = sdcardDir.getAbsolutePath();
                            }
                        }
                    }
                }
            }} catch (Exception e) {
            //Log.d(TAG+"getExternalPath--", " e:" + e);
        }
        return usb_path;
    }
    //检测文件或者文件夹是否存在
    public static boolean checkPath(String path)
    {
        if(path == null) return false;
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        return true;
    }

    //检测目录是否存在，不存在则创建
    public static boolean checkPathAndCreat(String folderPath)
    {
        File file = new File(folderPath);
        if (!file.exists())
        {
            if (file.mkdir())
            {
                LogUtil.debugLog("创建成功:"+folderPath);
                return true;
            }else {
                LogUtil.debugLog("创建失败:"+folderPath);
                return false;
            }
        }
        LogUtil.debugLog("目录已存在:"+folderPath);
        return true;
    }
    public static Boolean isEmptyFolder(String folderPath){
        if(folderPath == null) return true;
        if(new File((folderPath)).listFiles().length > 0) return false;
        return true;
    }


    //获取本机存储路径
    public static String getStoragePath() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        return path;
    }

    //获取屏保壁纸路径
    public static String getMyPhotosPath() {
        String path = getStoragePath() + MyPhotos;
        MyPathUtil.checkPathAndCreat(path);
        return path;
    }

    //获取所有外置存储路径(SD卡,U盘等)
    public static List<String> getAllExtPath( ) {
        List paths = getAllPath();
        paths.remove(getStoragePath());//移除内置存储路径
        LogUtil.debugLog("AllExtPath:"+paths);
        return paths;
    }

    //获取所有存储器路径
    public static List<String> getAllPath( ) {
        StorageManager mStorageManager = (StorageManager) NRTool.context().getSystemService(Context.STORAGE_SERVICE);
        List<StorageVolume> volumes = mStorageManager.getStorageVolumes();//此方法是android 7.0以上的
        List<String> paths = new ArrayList<>();
        try {
            Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
            //通过反射调用系统hide的方法
            Method getPath = storageVolumeClazz.getMethod("getPath");
            Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
            Method getUserLabel = storageVolumeClazz.getMethod("getUserLabel");

            for (int i = 0; i < volumes.size(); i++) {
                StorageVolume storageVolume = volumes.get(i);//获取每个挂载的StorageVolume
                // 通过反射调用getPath、isRemovable、userLabel
                String storagePath = (String) getPath.invoke(storageVolume); //获取路径
                boolean isRemovableResult = (boolean) isRemovable.invoke(storageVolume);//是否可移除
                String description = storageVolume.getDescription(NRTool.context());//此方法是android 7.0以上的
                String userLabel = (String) getUserLabel.invoke(storageVolume);
                paths.add(storagePath);
                LogUtil.debugLog("存储路径:"+storagePath+","+"label"+userLabel);
            }
        } catch (Exception e) {
            //Log.d(TAG+"getExternalPath--", " e:" + e);
        }
        return paths;
    }

    //路径获取文件名
    public static String getName(String path) {
        int start = path.lastIndexOf("/");
        int end = path.lastIndexOf(".");
        if (start != -1 && end != -1) {
            return path.substring(start + 1, end);
        } else {
            return null;
        }
    }
    //获取文件名不含后缀
    public static String getName(File file){
        String filename = file.getName();
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

    //路径获取文件名+扩展名
    public static String getNameAndExt(String path) {
        int start = path.lastIndexOf("/");
        int end = path.length();
        if (start != -1 && end != -1) {
            return path.substring(start + 1, end);
        } else {
            return null;
        }
    }
    //路径获取 扩展名
    public static String getExt(String path) {
        int start = path.lastIndexOf(".");
        int end = path.length();
        if (start != -1 && end != -1) {
            return path.substring(start, end);
        } else {
            return null;
        }
    }

}
